outf <- function(obj, file, sep="\t") {
    cat(obj, file=file, sep=sep)
    cat("\n", file=file)
}


setwd("/var/www/html/total/app/data/")

#引数
args <- commandArgs(trailingOnly=TRUE)

labelf <- args[1]
rawf <- args[2]
ofile <- paste("gt", args[3], ".txt", sep="")

rawf <- "rawdata-utf8.csv"
labelf <- "label-utf8.csv"
ofile <- "gt.txt"

labels <- read.csv(labelf, header=TRUE)
raws <- read.csv(rawf, header=TRUE)

#library(RJSONIO)

#rownames(labels) <- labels[,3]
#labelsj = toJSON(labels)
#cat(labelsj)

output <- file(ofile, open="w")

tables <- NULL
for ( i in 1:nrow(labels) ) {
    
    cate <- NULL
    tn <- NULL
    tp <- NULL
    t <- NULL

    label <- labels[i,]

    #サンプルNo列（設問タイプが空）とFAが対象外
    if (is.na(label$t) || label$t == "" || label$t == "FA") {
        next
    } else {
        #空行を出力
        cat("\n", file=output)

#        print(paste(label$la, label$nm));
#        cat(paste(label$la, label$nm), file=output, sep="\t")
#        cat("\n", file=output)

#        cate <- label[9:length(label)]
#        cate <- cate[cate != ""]
        
        print(label$la)
        cat(label$la, file=output)
        cat("\n", file=output)

    }
    
    if (label$t == "SA") {

        #無回答を含む
        tn <- table(raws[,label$cno], exclude=NULL);
        tn <- addmargins(tn)
        #tn <- c(tn, nrow(raws))

        #names(tn) <- c(cate, "<無回答>", "合計")

        tp <- tn/tn[length(tn)]*100


    } else if (label$t == "MA") {

        for (j in label$cno:label$cno2) {
            col <- subset(raws, raws[,j] == 1,c(j))
            tn <- c(tn, nrow(col))
        }
        #無回答
        colna <- subset(raws, is.na(raws[,label$cno]), c(label$cno))
        tn <- array(c(tn, nrow(colna)))

        #合計
        tn <- c(tn, nrow(raws))
        #names(tn) <- c(cate, "<無回答>", "合計")
        
        #MAの%は手動計算が必要
        tp <- tn/tn[length(tn)]*100

    } else if (label$t == "NU") {
        min <- min(raws[,label$cno])
        max <- max(raws[,label$cno])
        mean <- mean(raws[,label$cno])
        median <- median(raws[,label$cno])
        sum <- sum(raws[,label$cno])
        sd <- sd(raws[,label$cno])

        tn <- c(min, max, mean, median, sum, sd)
        tp <- tn

    }

    t <- list(N=tn, P=tp)

    print(t);
    write.table(t, file=output, append=T, quote=F, sep="\t", row.names=F, col.names=F )

    tables[label$la] <- t

}

#write.table(tables, file=output, append=T, quote=F, sep="\t", row.names=F, col.names=F )

library(RJSONIO)

tj = toJSON(tables)
cat(tj)

close(output)
